#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pycurl
import StringIO

def getPMC(id):
    start=id*10000
    url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
    buf = StringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.POST, 1)
    c.setopt(c.URL, url)
    c.setopt(pycurl.HTTPPOST, [('db', 'nuccore'), ('term', '28331[BioProject]'), ('retmode', 'json'), ('retmax', '10000'), ('retstart', str(start))])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    outfile = open("hmp_"+str(id)+".json", "w")
    outfile.write(buf.getvalue())
    outfile.close()
    buf.close()
    print "HMP task id " + str(id) + " has been successfully downloaded."

if __name__ == '__main__':
    for id in xrange(22):
        getPMC(id)